package com.zxf.basic.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding

/**
 * @author zjc
 * @date 2022/12/28
 */
open class BindingAdapter<T : Any, VB : ViewBinding>(
    private val inflate: (layoutInflater: LayoutInflater, parent: ViewGroup, attchParent: Boolean) -> VB,
    private val block: VB.(T, MutableList<Any>?) -> Unit
    ) : BaseAdapter<T>() {

    override fun layout() = 0

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val binding = inflate.invoke(LayoutInflater.from(parent.context), parent, false)
        return BindingHolder(binding)
    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
        block.invoke((holder as BindingAdapter<T, VB>.BindingHolder).binding, getData()[position], null)
    }

    override fun onBindViewHolder(holder: Holder, position: Int, payloads: MutableList<Any>) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
            return
        }
        block.invoke((holder as BindingAdapter<T, VB>.BindingHolder).binding, getData()[position], payloads)
    }

    inner class BindingHolder(val binding: VB) : Holder(binding.root)

}